package com.bins.rabbitmq.producer;

import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.bins.rabbitmq.entity.UserEntity;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class RabbitmqProducer {

	@Autowired
	private RabbitTemplate rabbitTemplate;

	public void sendWork() {
		for (int i = 0; i < 10; i++) {
			rabbitTemplate.convertAndSend("work_queue", "测试work模型: " + i);
		}
	}

	public void sendPublish() {
		for (int i = 0; i < 5; i++) {
			rabbitTemplate.convertAndSend("fanout_exchange", "", "测试发布订阅模型：" + i);
		}
	}

	public void sendTopic() {
		for (int i = 0; i < 10; i++) {
			if (i % 2 == 0) {
				rabbitTemplate.convertSendAndReceive("exchange_topic", "topic.km.topic", "测试发布订阅模型：" + i);
			} else {
				rabbitTemplate.convertSendAndReceive("exchange_topic", "topic.km", "测试发布订阅模型：" + i);
			}
		}
	}
	
	private final RabbitTemplate.ConfirmCallback confirmCallback = new RabbitTemplate.ConfirmCallback() {
	    @Override
	    public void confirm(CorrelationData correlationData, boolean b, String s) {
	        if (b) {
	        	log.info("confirm 消息确认成功..." + correlationData.getId());
	        } else {
	        	log.info("confirm 消息确认失败..." + correlationData.getId() + " cause: " + s);
	        }
	    }
	};

	public void sendConfirm() {
		UserEntity user = new UserEntity();
		user.setId(getRamdomLong());
		user.setUserName("andy");
		user.setPhone("18899998888");
		user.setSex(1);
		user.setAge(20);
	    rabbitTemplate.convertAndSend("confirm_queue", user, new CorrelationData("" + System.currentTimeMillis()));
	    rabbitTemplate.setConfirmCallback(confirmCallback);
	}

	private Long getRamdomLong() {
		Long random = 0l;
		try {
			random = SecureRandom.getInstance("SHA1PRNG").nextLong();
		} catch (NoSuchAlgorithmException e) {
			log.error("getRamdomLong", e);
		}
		return random;
	}
	
	private final RabbitTemplate.ReturnCallback returnCallback = new RabbitTemplate.ReturnCallback() {

        @Override
        public void returnedMessage(Message message, int i, String s, String s1, String s2) {
        	log.info(message == null ? "" : message.toString());
        	log.info(new String(message.getBody()));
        	log.info(String.valueOf(i));
        	log.info(s);
        	log.info(s1);
        	log.info(s2);
        }
    };

    public void sendReturn() {
        rabbitTemplate.setReturnCallback(returnCallback);
        // rabbitTemplate.convertAndSend("return_exchange", "return.km.km", "测试 return 机制");
        rabbitTemplate.convertAndSend("exchange_return", "return.km", "测试 return 机制");
    }
}